<?php

declare(strict_types=1);

namespace app\yperp\command;

use Facebook\WebDriver\Exception\NoSuchWindowException;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Fastposter\Client as FastposterClient;
use think\console\Command;
use think\console\Input;

use think\console\Output;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Stream;
use InvalidArgumentException;
use RuntimeException;
use think\facade\Cache;
use app\yperp\logic\Brand as LogicBrand;

class ocr extends Command
{

    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];
    protected function configure()
    {
        // 指令配置
        $this->setName('ocr')
            ->setDescription('测试命令：ocr');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;
        $code_img_path = env('root_path') . 'runtime' . DIRECTORY_SEPARATOR . 'mgt_code.png';
        dump(file_exists($code_img_path));
        dump($code_img_path);
        $user_captcha_ = $this->ocrApi($code_img_path, 'http://127.0.0.1:5000/ocr');
        dump($user_captcha_);
    }

    function ocrApi($imgPath, $apiUrl = 'http://ocrapi.jzzw-tech.cn/ocr')
    {
        // 检查文件是否存在
        if (!file_exists($imgPath)) {
            throw new InvalidArgumentException("File not found at path: {$imgPath}");
        }

        // 初始化cURL会话
        $ch = curl_init();

        // 设置cURL选项
        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => ['image' => new \CurlFile($imgPath)],
            CURLOPT_HTTPHEADER => ['Content-Type: multipart/form-data'],
        ]);

        // 执行cURL请求
        $response = curl_exec($ch);

        // 检查cURL错误
        if (curl_errno($ch)) {
            throw new RuntimeException('cURL error: ' . curl_error($ch));
        }

        // 获取HTTP响应状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭cURL会话
        curl_close($ch);

        // 根据HTTP响应状态码处理结果
        if ($httpCode !== 200) {
            throw new RuntimeException('Failed to upload image. Server responded with status code: ' . $httpCode);
        }

        // 返回响应内容
        return json_decode($response, true);
    }
}
